package com.mtl.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@RestController
@RequestMapping("article")

public class ImageCodeController extends HttpServlet {
    @Autowired
    protected Color getColor(){
        Random random=new Random();
        int r=random.nextInt(256);
        int g=random.nextInt(256);
        int b=random.nextInt(256);
        return new Color(r,g,b);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
    @GetMapping("/image")
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("image/jpeg;charset=UTF-8");
        int width=80;
        int height=28;
        int imageType= BufferedImage.TYPE_INT_RGB;
        String str="0123456789qwertyuiopasdfghjklzxcvbnm";
        StringBuffer checkCode=new StringBuffer();
        HttpSession session=request.getSession();
        session.setAttribute("checkCode",checkCode);
        Random random=new Random();
        BufferedImage image=new BufferedImage(width,height,imageType);
        Graphics g=image.getGraphics();
        g.fillRect(0,0,width,height);
        for (int i = 0; i <10 ; i++) {
            int xBegin=random.nextInt(width);
            int yBegin=random.nextInt(height);
            int xEnd=random.nextInt(width);
            int yEnd=random.nextInt(height);
            g.setColor(getColor());
            g.drawLine(xBegin,yBegin,xEnd,yEnd);
        }
        g.setFont(new Font("宋体",Font.BOLD,25));
        for (int i = 0; i <4 ; i++) {
            g.setColor(getColor());
            String s=String.valueOf(str.charAt(random.nextInt(str.length())));
            checkCode.append(s);
            g.drawString(s,20*i,20);
        }
        ImageIO.write(image,"jpeg",response.getOutputStream());

        //设置无缓存
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setHeader("Expires","0");

    }
}
